import { mapGetters } from 'vuex'
export default {
  props: ['rowData'],
  computed: {
    ...mapGetters(['areaTree'])
  },
  data () {
    return {
      showDialog: true,
      selected: [],
      lock: true,
      loadingBtn: false
    }
  },
  watch: {
    showDialog (n) {
      if (!n) {
        this.$emit('closeDialog')
      }
    },
    // 列表状态改变
    'list.loading' (n) {
      this.$nextTick(() => {
        if (!n) {
          // 回显已选中的
          this.selected.forEach(item => {
            this.toggleRowSelection(item, true)
          })
        }
        // 加锁的原因是因为边个初始化时会调用handleSelectionChange并传入空数组，会清空已选择的内容
        this.lock = n
      })
    }
  },
  methods: {
    show () {
      this.showDialog = true
    },
    // 列表选择状态改变
    handleSelectionChange (e) {
      if (this.lock) {
        return // 锁住的，退出
      }
      // 先删除全部
      this.list.data.forEach(item => {
        this.removeItem(item)
      })
      e.forEach(item => {
        // 在添加
        this.addItem(item)
      })
    },
    // 是否已经勾选
    isSelected (row) {
      return this.selected.some(item => item[this.idKey] == row[this.idKey])
    },
    // 添加一项
    addItem (row) {
      this.selected.unshift(row)
      this.$forceUpdate()
    },
    // 删除一项
    removeItem (row) {
      this.selected = this.selected.filter(
        item => item[this.idKey] !== row[this.idKey]
      )
      this.$forceUpdate()
    },
    // 切换选中状态
    toggleRowSelection (row, status) {
      if (!status) {
        this.removeItem(row)
      }
      // 切换某一行的选中状态
      this.list.data.forEach(item => {
        if (row[this.idKey] === item[this.idKey]) {
          this.$refs.tableList.toggleRowSelection(item, status)
          return
        }
      })
    },
    submitFormFun () {
      if (this.selected.length == 0) {
        this.$swal.error(this.nullTip || '未勾选任何数据')
      } else {
        this.loadingBtn = true
        this.$POST('sot-admin-api/sys/department/addDataPerm', {
          departmentId: this.rowData.departmentId,
          dataType: this.dataType,
          dataList: this.selected.map(item => item[this.idKey])
        })
          .then(res => {
            if (res.errorCode == '00000') {
              this.$swal.success('设置成功')
              this.showDialog = false
            } else {
              this.$swal.error(res.message)
            }
          })
          .finally(_ => {
            this.loadingBtn = false
          })
      }
    }
  },
  filters: {
    auditStatus (code) {
      const status = {
        0: '资料待审核',
        1: '待审核',
        2: '审核通过',
        3: '审核驳回'
      }
      return status[code] || ''
    }
  }
}
